(* A compiler avec ocamlopt, puis a utiliser en pipe *)

open Bplib
let args = Array.to_list Sys.argv;;
let args_assoc = assoc_of_sys_argv Sys.argv;;
let get_arg_int_value = try_get_arg_int_value args_assoc;;
let get_arg_string_value = try_get_arg_string_value args_assoc;;
let _f = get_arg_int_value "-f";;

(* On peut instancier l'objet *)
let pause = new Bplib.sleeper (1./.(float_of_int _f)) false;;

(* Il y a 2 possibilités : *)
(* 
   - Soit on est en mode -start avec changements durables
   - Soit on est en mode -default avec changements sur 1 cycle
*)

let mode_start start =
  try
    let line = ref start in
    let thread_1 () =
      while true do
	pause#sleep;
	print_endline (!line)
      done
    in
    let thread_2 () = 
      while true do
	let new_line = input_line stdin in
	line := new_line
      done
    in
    ignore(Thread.create thread_1 ());
    thread_2 ()
  with
  | End_of_file -> ()


let mode_default default duree = 
  let q = Queue.create () in
  try
    let count = ref 0 in
    let line = ref default in
    let thread_1 () =
      while true do
	incr(count);
	pause#sleep;
	if !count <= duree
	then print_endline (!line)
	else 
	  begin
	    if Queue.is_empty q
	    then print_endline default
	    else
	      begin
		line := Queue.pop q;
		count := 1;
		print_endline (!line)
	      end
	  end
      done
    in
    let thread_2 () = 
      while true do
	let new_line = input_line stdin in
	Queue.push new_line q
      done
    in
    ignore(Thread.create thread_1 ());
    thread_2 ()
  with
  | End_of_file -> ()

let _ =
  if List.mem "-s" args
  then
    (* Mode start *) 
    let start = get_arg_string_value "-s" in
    mode_start start
  else
  if List.mem "-d" args
  then
    (* Mode default *)
    let default = get_arg_string_value "-d" in
    let duree = get_arg_int_value "-cy" in
    mode_default default duree
  else
    (* Mode default avec premiere ligne lue pour default *)
    Printf.fprintf stderr "Default Line : "; flush stderr;
    let default = input_line stdin in
    let duree = get_arg_int_value "-cy" in
    mode_default default duree
    
